# encoding=utf-8
import csv
import json
import os
import sys
import threading
import time

import requests

abs_path = os.path.split(sys.argv[0])[0]

'''
获取音乐的请求, 分析json数据, 将 音乐名称,hash,id 获取出来
'''


# 将请求的数据, 转换成json数据
def get_true_json(conn, key=False):
    index = conn.find('(') + 1
    conn = conn[index:-2]
    if not key:
        return conn
    else:
        return json.loads(conn, encoding='utf-8')


# 获取音乐数据
def get_data_json(data_url):

    conn = requests.get(url=data_url)
    conn.encoding = 'utf-8'

    conn = get_true_json(conn.text, True)

    return conn['data']


# 打印json数据
def data_print_to_save(conn):

    audio_name = conn.get('audio_name')
    album_id = conn.get('album_id')
    author_id = conn.get('author_id')
    author_name = conn.get('author_name')
    song_name = conn.get('song_name')
    hash = conn.get('hash')
    play_url = conn.get('play_url')
    lyrics = conn.get('lyrics')

    print([audio_name, author_name, song_name, play_url])
    save_lyric(audio_name, lyrics)

    # 下载歌曲
    download_music(audio_name, play_url)



# 保存 list 为csv文件
def save_csv(list_li):
    thLock = threading.Lock()
    thLock.acquire()
    file_path = abs_path + '/' + 'music_url.csv'
    f = open(file_path, 'a+', encoding='utf-8', newline='')
    writer = csv.writer(f)
    writer.writerow(list_li)
    f.close()
    thLock.release()


# 下载歌曲, 需要创建 music文件夹
def download_music(audio_name, play_url):
    folder_path = abs_path + '/' + 'music/'
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)

    music_type = play_url.split('.')[-1]

    print(audio_name, play_url, music_type)

    if '' == play_url:
        print('play_url is null')
        return 0

    try:
        conn = requests.get(play_url)
        with open(folder_path + audio_name + '.' + music_type, 'wb') as f:
            f.write(conn.content)
    except Exception as e:
        with open(abs_path + '/' + 'error.txt', 'a+') as f:
            f.write(audio_name + '\n')
            f.write(play_url + '\n')
            f.write('--------------------------' + '\n')



# 保存歌词文件
def save_lyric(name, words):
    thLock = threading.Lock()
    file_type = '.lrc'
    folder_path = abs_path + '/' + 'music/'
    if not os.path.isdir(folder_path):
        os.mkdir(folder_path)

    thLock.acquire()
    if words == '':  # 歌词为空返回
        return
    if '' == name:  # 文件名称为空,获取时间帧为文件名
        name = str(time.time_ns())
    file_path = folder_path + name + file_type

    f = open(file_path, 'w', encoding='utf-8')
    f.write(words)
    f.close()
    thLock.release()


# 记录 data.json 数据
def count_data_json():
    with open('data.json', 'r', encoding='utf-8') as f:
        jsonStr = json.load(f)
        json_li = jsonStr['data']['lists']
        for i in json_li:
            print(i)

        print('json list count : ', len(json_li))


if __name__ == '__main__':
    # 在这里替换url
    data_url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19103605403736321413_1560952366193&hash=B5A2D566C9DE70422F5E5E7203054219&album_id=6960309&dfid=2kyjrz3ykJUd0AvWbR4O30yK&mid=331960782911d3b3792b4f367192d955&platid=4&_=1560952366203'

    conn = get_data_json(data_url)
    data_print_to_save(conn)

    # count_data_json()
    # save_lyric('hehehe', 'fjdsaoejfaslkjfioeajfdklsjafioejfals')
